#define _CRT_SECURE_NO_WARNINGS

#include "list.h"


ListNode* ListCreate()
{
	ListNode* headnode = (ListNode*)malloc(sizeof(ListNode));
	if (!headnode)
	{
		perror("malloc failed");
		return;
	}
	headnode->_data = -1;
	headnode->_next = headnode;
	headnode->_prev = headnode;
}

void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->_next;
	while (cur != pHead)
	{
		ListNode* next = cur->_next;
		free(cur);
		cur = next;
	}
	free(pHead);
}

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->_next;
	printf("<=>head<=>");
	while (cur != pHead)
	{
		printf("%d<=>", cur->_data);
		cur = cur->_next;
	}
	printf("\n");
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* tail = pHead->_prev;
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (!newnode)
	{
		perror("malloc failed");
		return;
	}
	newnode->_data = x;
	newnode->_next = pHead;
	newnode->_prev = tail;
	tail->_next = newnode;
	pHead->_prev = newnode;
	//ListInsert(pHead, x)
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(!(pHead == pHead->_next));
	ListNode* tail = pHead->_prev;
	ListNode* prev = tail->_prev;
	pHead->_prev = prev;
	prev->_next = pHead;
	free(tail);
	tail = NULL;
	//ListErase(pHead->_prev);
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	ListNode* next = pHead->_next;
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (!newnode)
	{
		perror("malloc failed");
		return;
	}
	newnode->_data = x;
	newnode->_prev = pHead;
	newnode->_next = next;
	pHead->_next = newnode;
	next->_prev = newnode;
	//ListInsert(pHead->_next, x)
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(!(pHead == pHead->_next));
	ListNode* next = pHead->_next->_next;
	ListNode* cur = pHead->_next;
	pHead->_next = next;
	next->_prev = pHead;
	free(cur);
	cur = NULL;
	//ListErase(pHead->_next)
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* cur = pHead->_next;
	while (cur != pHead)
	{
		if (cur->_data = x)
			return cur;
		cur = cur->_next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (!newnode)
	{
		perror("malloc failed");
		return;
	}
	newnode->_data = x;
	ListNode* prev = pos->_prev;
	newnode->_prev = prev;
	newnode->_next = pos;
	prev->_next = newnode;
	pos->_prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* next = pos->_next;
	ListNode* prev = pos->_prev;
	next->_prev = prev;
	prev->_next = next;
	free(pos);
}